
const _interopRequireDefault = require('@babel/runtime/helpers/interopRequireDefault');

exports.__esModule = true;
exports.default = void 0;

const _extends2 = _interopRequireDefault(require('@babel/runtime/helpers/extends'));

const _utils = require('../utils');

const _mobile = require('../utils/validate/mobile');

const _area = _interopRequireDefault(require('../area'));

const _field = _interopRequireDefault(require('../field'));

const _popup = _interopRequireDefault(require('../popup'));

const _toast = _interopRequireDefault(require('../toast'));

const _button = _interopRequireDefault(require('../button'));

const _dialog = _interopRequireDefault(require('../dialog'));

const _Detail = _interopRequireDefault(require('./Detail'));

const _switchCell = _interopRequireDefault(require('../switch-cell'));

// Utils
// Components
const _createNamespace = (0, _utils.createNamespace)('address-edit');
const createComponent = _createNamespace[0];
const bem = _createNamespace[1];
const t = _createNamespace[2];

const defaultData = {
  name: '',
  tel: '',
  country: '',
  province: '',
  city: '',
  county: '',
  areaCode: '',
  postalCode: '',
  addressDetail: '',
  isDefault: false,
};

function isPostal(value) {
  return /^\d{6}$/.test(value);
}

const _default2 = createComponent({
  props: {
    areaList: Object,
    isSaving: Boolean,
    isDeleting: Boolean,
    validator: Function,
    showDelete: Boolean,
    showPostal: Boolean,
    searchResult: Array,
    showSetDefault: Boolean,
    showSearchResult: Boolean,
    saveButtonText: String,
    deleteButtonText: String,
    areaPlaceholder: String,
    showArea: {
      type: Boolean,
      default: true,
    },
    showDetail: {
      type: Boolean,
      default: true,
    },
    disableArea: Boolean,
    detailRows: {
      type: [Number, String],
      default: 1,
    },
    detailMaxlength: {
      type: [Number, String],
      default: 200,
    },
    addressInfo: {
      type: Object,
      default: function _default() {
        return (0, _extends2.default)({}, defaultData);
      },
    },
    telValidator: {
      type: Function,
      default: _mobile.isMobile,
    },
    postalValidator: {
      type: Function,
      default: isPostal,
    },
    areaColumnsPlaceholder: {
      type: Array,
      default: function _default() {
        return [];
      },
    },
  },
  data: function data() {
    return {
      data: {},
      showAreaPopup: false,
      detailFocused: false,
      errorInfo: {
        tel: '',
        name: '',
        areaCode: '',
        postalCode: '',
        addressDetail: '',
      },
    };
  },
  computed: {
    areaListLoaded: function areaListLoaded() {
      return (0, _utils.isObject)(this.areaList) && Object.keys(this.areaList).length;
    },
    areaText: function areaText() {
      const _this$data = this.data;
      const { country } = _this$data;
      const { province } = _this$data;
      const { city } = _this$data;
      const { county } = _this$data;
      const { areaCode } = _this$data;

      if (areaCode) {
        const arr = [country, province, city, county];

        if (province && province === city) {
          arr.splice(1, 1);
        }

        return arr.filter((text) => text).join('/');
      }

      return '';
    },
  },
  watch: {
    addressInfo: {
      handler: function handler(val) {
        this.data = (0, _extends2.default)({}, defaultData, {}, val);
        this.setAreaCode(val.areaCode);
      },
      deep: true,
      immediate: true,
    },
    areaList: function areaList() {
      this.setAreaCode(this.data.areaCode);
    },
  },
  methods: {
    onFocus: function onFocus(key) {
      this.errorInfo[key] = '';
      this.detailFocused = key === 'addressDetail';
      this.$emit('focus', key);
    },
    onChangeDetail: function onChangeDetail(val) {
      this.data.addressDetail = val;
      this.$emit('change-detail', val);
    },
    onAreaConfirm: function onAreaConfirm(values) {
      values = values.filter((value) => !!value);

      if (values.some((value) => !value.code)) {
        (0, _toast.default)(t('areaEmpty'));
        return;
      }

      this.showAreaPopup = false;
      this.assignAreaValues();
      this.$emit('change-area', values);
    },
    assignAreaValues: function assignAreaValues() {
      const { area } = this.$refs;

      if (area) {
        const detail = area.getArea();
        detail.areaCode = detail.code;
        delete detail.code;
        (0, _extends2.default)(this.data, detail);
      }
    },
    onSave: function onSave() {
      const _this = this;

      const items = ['name', 'tel'];

      if (this.showArea) {
        items.push('areaCode');
      }

      if (this.showDetail) {
        items.push('addressDetail');
      }

      if (this.showPostal) {
        items.push('postalCode');
      }

      const isValid = items.every((item) => {
        const msg = _this.getErrorMessage(item);

        if (msg) {
          _this.errorInfo[item] = msg;
        }

        return !msg;
      });

      if (isValid && !this.isSaving) {
        this.$emit('save', this.data);
      }
    },
    getErrorMessage: function getErrorMessage(key) {
      const value = String(this.data[key] || '').trim();

      if (this.validator) {
        const message = this.validator(key, value);

        if (message) {
          return message;
        }
      }

      switch (key) {
        case 'name':
          return value ? '' : t('nameEmpty');

        case 'tel':
          return this.telValidator(value) ? '' : t('telInvalid');

        case 'areaCode':
          return value ? '' : t('areaEmpty');

        case 'addressDetail':
          return value ? '' : t('addressEmpty');

        case 'postalCode':
          return value && !this.postalValidator(value) ? t('postalEmpty') : '';
      }
    },
    onDelete: function onDelete() {
      const _this2 = this;

      _dialog.default.confirm({
        title: t('confirmDelete'),
      }).then(() => {
        _this2.$emit('delete', _this2.data);
      }).catch(() => {
        _this2.$emit('cancel-delete', _this2.data);
      });
    },
    // get values of area component
    getArea: function getArea() {
      return this.$refs.area ? this.$refs.area.getValues() : [];
    },
    // set area code to area component
    setAreaCode: function setAreaCode(code) {
      this.data.areaCode = code || '';

      if (code) {
        this.$nextTick(this.assignAreaValues);
      }
    },
    // @exposed-api
    setAddressDetail: function setAddressDetail(value) {
      this.data.addressDetail = value;
    },
    onDetailBlur: function onDetailBlur() {
      const _this3 = this;

      // await for click search event
      setTimeout(() => {
        _this3.detailFocused = false;
      });
    },
  },
  render: function render() {
    const _this4 = this;

    const h = arguments[0];
    const { data } = this;
    const { errorInfo } = this;
    const { searchResult } = this;
    const { disableArea } = this;

    const onFocus = function onFocus(name) {
      return function () {
        return _this4.onFocus(name);
      };
    }; // hide bottom field when use search && detail get focused


    const hideBottomFields = searchResult && searchResult.length && this.detailFocused;
    return h('div', {
      class: bem(),
    }, [h('div', {
      class: bem('fields'),
    }, [h(_field.default, {
      attrs: {
        clearable: true,
        label: t('name'),
        placeholder: t('namePlaceholder'),
        errorMessage: errorInfo.name,
      },
      on: {
        focus: onFocus('name'),
      },
      model: {
        value: data.name,
        callback: function callback($$v) {
          _this4.$set(data, 'name', $$v);
        },
      },
    }), h(_field.default, {
      attrs: {
        clearable: true,
        type: 'tel',
        label: t('tel'),
        placeholder: t('telPlaceholder'),
        errorMessage: errorInfo.tel,
      },
      on: {
        focus: onFocus('tel'),
      },
      model: {
        value: data.tel,
        callback: function callback($$v) {
          _this4.$set(data, 'tel', $$v);
        },
      },
    }), h(_field.default, {
      directives: [{
        name: 'show',
        value: this.showArea,
      }],
      attrs: {
        readonly: true,
        clickable: !disableArea,
        label: t('area'),
        placeholder: this.areaPlaceholder || t('areaPlaceholder'),
        errorMessage: errorInfo.areaCode,
        rightIcon: !disableArea ? 'arrow' : null,
        value: this.areaText,
      },
      on: {
        focus: onFocus('areaCode'),
        click: function click() {
          _this4.$emit('click-area');

          _this4.showAreaPopup = !disableArea;
        },
      },
    }), h(_Detail.default, {
      directives: [{
        name: 'show',
        value: this.showDetail,
      }],
      attrs: {
        focused: this.detailFocused,
        value: data.addressDetail,
        errorMessage: errorInfo.addressDetail,
        detailRows: this.detailRows,
        detailMaxlength: this.detailMaxlength,
        searchResult: this.searchResult,
        showSearchResult: this.showSearchResult,
      },
      on: {
        focus: onFocus('addressDetail'),
        blur: this.onDetailBlur,
        input: this.onChangeDetail,
        'select-search': function selectSearch(event) {
          _this4.$emit('select-search', event);
        },
      },
    }), this.showPostal && h(_field.default, {
      directives: [{
        name: 'show',
        value: !hideBottomFields,
      }],
      attrs: {
        type: 'tel',
        maxlength: '6',
        label: t('postal'),
        placeholder: t('postal'),
        errorMessage: errorInfo.postalCode,
      },
      on: {
        focus: onFocus('postalCode'),
      },
      model: {
        value: data.postalCode,
        callback: function callback($$v) {
          _this4.$set(data, 'postalCode', $$v);
        },
      },
    }), this.slots()]), this.showSetDefault && h(_switchCell.default, {
      class: bem('default'),
      directives: [{
        name: 'show',
        value: !hideBottomFields,
      }],
      attrs: {
        title: t('defaultAddress'),
      },
      on: {
        change: function change(event) {
          _this4.$emit('change-default', event);
        },
      },
      model: {
        value: data.isDefault,
        callback: function callback($$v) {
          _this4.$set(data, 'isDefault', $$v);
        },
      },
    }), h('div', {
      directives: [{
        name: 'show',
        value: !hideBottomFields,
      }],
      class: bem('buttons'),
    }, [h(_button.default, {
      attrs: {
        block: true,
        round: true,
        loading: this.isSaving,
        type: 'danger',
        text: this.saveButtonText || t('save'),
      },
      on: {
        click: this.onSave,
      },
    }), this.showDelete && h(_button.default, {
      attrs: {
        block: true,
        round: true,
        loading: this.isDeleting,
        text: this.deleteButtonText || t('delete'),
      },
      on: {
        click: this.onDelete,
      },
    })]), h(_popup.default, {
      attrs: {
        position: 'bottom',
        lazyRender: false,
        getContainer: 'body',
      },
      model: {
        value: _this4.showAreaPopup,
        callback: function callback($$v) {
          _this4.showAreaPopup = $$v;
        },
      },
    }, [h(_area.default, {
      ref: 'area',
      attrs: {
        loading: !this.areaListLoaded,
        value: data.areaCode,
        areaList: this.areaList,
        columnsPlaceholder: this.areaColumnsPlaceholder,
      },
      on: {
        confirm: this.onAreaConfirm,
        cancel: function cancel() {
          _this4.showAreaPopup = false;
        },
      },
    })])]);
  },
});

exports.default = _default2;
